Imports System.Data.SqlClient
Imports system.Security.Cryptography
Imports System.IO
Imports System.Text

Friend Class DBScanVText
    Inherits DBBase

    Private moServer As SQLAutoDocLib.Server
    Private moDatabase As SQLAutoDocLib.Database
    Private moLogin As SQLAutoDocLib.Login
    Private moView As SQLAutoDocLib.View

    Public Sub New( _
            ByVal oServer As SQLAutoDocLib.Server, _
            ByVal oDatabase As SQLAutoDocLib.Database, _
            ByVal oLogin As SQLAutoDocLib.Login, _
            ByVal oView As SQLAutoDocLib.View)

        moServer = oServer
        moDatabase = oDatabase
        moLogin = oLogin
        moView = oView
    End Sub

    Public Sub Scan( _
                ByRef sViewText As String, _
                ByRef sTextHash As String)

        sViewText = ScanForText()
        sTextHash = ComputeSHA1(sViewText)
    End Sub

    Private Function ScanForText() As String
        Dim sText As New StringBuilder

        Dim sSQL As String = "select"
        sSQL = sSQL & "     a.[text],"
        sSQL = sSQL & "     a.[encrypted]"
        sSQL = sSQL & " from "
        sSQL = sSQL & " dbo.syscomments a "
        sSQL = sSQL & "                  join dbo.sysobjects b on b.[id]=a.[id]"
        sSQL = sSQL & "                  join dbo.sysusers c on c.[uid]=b.[uid]"
        sSQL = sSQL & "  where"
        sSQL = sSQL & "     b.[type]='V'"
        sSQL = sSQL & "     and b.[name]=" & ValueToDBValue(moView.Name)
        sSQL = sSQL & "     and c.[name]=" & ValueToDBValue(moLogin.Login)
        sSQL = sSQL & "  order by"
        sSQL = sSQL & "     a.[colid]"

        Dim oData As DataTable = MyBase.ExecuteReadToDataTable(sSQL, moDatabase.DecryptedConnectionString)

        If oData.Rows.Count > 0 Then
            If oData.Rows(0).Item("encrypted") = 1 Then
                sText.Append("The object comments have been encrypted.")

            Else
                For Each oRow As DataRow In oData.Rows
                    sText.Append(oRow.Item(0))
                Next
            End If
        Else
            sText.Append("No source exists for this object.")
        End If

        oData.Dispose()

        Return sText.ToString
    End Function

    Private Function ComputeSHA1(ByVal sViewText As String) As String
        Dim sha As New SHA1CryptoServiceProvider()

        Dim oEncoding As System.Text.ASCIIEncoding = New System.Text.ASCIIEncoding
        Dim oFieldBytes As Byte() = oEncoding.GetBytes(sViewText)

        Dim oHashBytes As Byte() = sha.ComputeHash(oFieldBytes)
        Dim sHash As String = oEncoding.GetString(oHashBytes)

        Return sHash
    End Function
End Class
